﻿using DingChiServiceApp.db;
using DingChiServiceApp.entity;
using DingChiServiceApp.helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DingChiServiceApp
{
    public class DataSyncHelper
    {
        /// <summary>
        /// upload data
        /// </summary>
        public static void Up()
        {
            LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();
            //DateTime stop = DateTime.Parse(localConfig.StopDateTime);
            //if(DateTime.Now > stop) { return ; }

            HaulBillDao Dao = new HaulBillDao();
            //-- Ding Chi Service On sync data，
            LogHelper.FileLog(DateTime.Now.ToString(GlobalConstract.datetime_format) + " 开始同步数据");
     
            int rows = localConfig.maxRows;
      
            string url = localConfig.baseUrl;
            if (string.IsNullOrEmpty(url))
            {
                LogHelper.FileLog(" ---------- 服务器地址错误。");
                return;
            }   
            if (rows <= 0) rows = 5;
            string startTime = localConfig.StartDateTime;           
            var datas = Dao.SelectNoUps(rows,startTime);
            if (datas == null || datas.Count <= 0)
            {
                LogHelper.FileLog(" ---------- 没有数据需要上传。");
                return;
            }
            else
            {
                LogHelper.FileLog($" ---------- 有{datas.Count}条数据需要上传。");
            }
            string token = "";
            var requestParam = new KeyValuePair<string, string>();
            var headers = new KeyValuePair<string, string>("token", token);
            int successCount= 0 ;
            int errorCount=0;
            int i = 0;
            for (; i < datas.Count(); i++)
            {
                HaulBill bill = datas[i];
                bool isOk = false;
                //successCount = 0;
                 //errorCount = 0;
                try
                {
                    var duplicate = DuplicateHelper.Create(bill);
                    string postJsonData = JsonHelper.ObjectToJsonIso(duplicate);
                    //string data = "tDuplicate="+ postJsonData;
                    var result = HttpWebRequestHelper.Post(url, postJsonData, headers, requestParam, false);
                    if (result.Code == 200 || result.Code == 201)
                    {
                        isOk = true;//只要返回 200 代表上传成功
                        successCount++;
                       // LogHelper.FileLog("上传数据成功：" + duplicate.duplicateCode );

                        //TODO 成功 状态
                        //if (duplicate.id.ToString() == (string)result.Data)
                        //{
                        //    LogHelper.FileLog("上传数据成功：" + duplicate.duplicateCode + "返回：" + result.Data);
                        //    //upStatus.lastUpTime = duplicate.updateTime != null  ? duplicate.updateTime : duplicate.createTime;
                        //    isOk = true;
                        //}
                        //else
                        //{
                        //    LogHelper.FileLog("上传数据失败：" + duplicate.duplicateCode + "返回：" + result.Data);
                        //    isOk = false;
                        //}
                    }
                    else
                    {
                        LogHelper.FileLog("上传数据错误：" + duplicate.duplicateCode + "状态码："+ result.Code + "; 消息：" + result.Msg);
                        isOk = false;
                        errorCount++;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.FileLog("上传数据异常 " + ex.Message);
                    errorCount++;
                }
                finally
                {
                    if (isOk)
                    {
                        bill.isUpGovernment = 1;
                         int res =  Dao.UpdateUpGoverment(bill);
                        Console.WriteLine(bill.id + " " + bill.duplicateId + " code:" + bill.serial+ "res:"+res);
                    }
                    //UpStatusJsonDao.Instance.Update(upStatus);
                }
            }

            string msgTemplate = $" 上传结束,成功: {successCount}，失败 {errorCount}。";
            LogHelper.FileLog(msgTemplate);
        }

        /// <summary>
        /// Repetition upload data than the up data on modifly
        /// </summary>
        public static void  RepetitionUp()
        {
            LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();  
            HaulBillDao Dao = new HaulBillDao();
            int rows = 1;
            string url = localConfig.baseUrl;
            if (string.IsNullOrEmpty(url))
            {
                LogHelper.FileLog(" ---------- 服务器地址错误。");
                return;
            }
            if (rows <= 0) rows = 5;         
            UpStatus upStatus = UpStatusJsonDao.Instance.FindByTableName(GlobalConstract.duplicate_tableName);
            string lastTime = localConfig.StartDateTime;        
            List<HaulBill> datas = Dao.SelectNeedRepetitionUploads(rows, lastTime);
           
            if (datas == null || datas.Count <= 0)
            {
                LogHelper.FileLog(" ---------- 没有数据需要重先上传。");
                return;
            }
            else
            {
                LogHelper.FileLog($" ---------- 有{datas.Count}条数据需要重先上传。");
            }
            string token = "";
            var requestParam = new KeyValuePair<string, string>();
            var headers = new KeyValuePair<string, string>("token", token);
            int successCount = 0;
            int errorCount = 0;
            int i = 0;
            for (; i < datas.Count(); i++)
            {
                HaulBill bill = datas[i];
                bool isOk = false;
                try
                {
                    var duplicate = DuplicateHelper.Create(bill);
                    string postJsonData = JsonHelper.ObjectToJsonIso(duplicate);
                    var result = HttpWebRequestHelper.Post(url, postJsonData, headers, requestParam, false);
                    if (result.Code == 200 || result.Code == 201)
                    {
                        isOk = true;//只要返回 200 代表上传成功
                        successCount++;                   
                    }
                    else
                    {
                        LogHelper.FileLog("重先上传数据错误：" + duplicate.duplicateCode + "状态码：" + result.Code + "; 消息：" + result.Msg);
                        isOk = false;
                        errorCount++;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.FileLog("重先上传数据异常 " + ex.Message);
                    errorCount++;
                }
                finally
                {
                    if (isOk)
                    {
                        upStatus.lastUpTime = bill.modifyTime != null ? bill.modifyTime : bill.createTime;
                        int res = UpStatusJsonDao.Instance.Update(upStatus);
                        Console.WriteLine(bill.id + " " + bill.duplicateId + " code:" + bill.serial + "res:" + res);
                    }                  
                }
            }

            string msgTemplate = $" 重先上传结束,成功: {successCount}，失败 {errorCount}。";
            LogHelper.FileLog(msgTemplate);
        }

    }
}
